package com.sgb.kjwl.view.ui.activity.self.publish;

import android.content.Context;
import android.content.Intent;

import androidx.databinding.DataBindingUtil;

import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityCarPublish2Binding;
import com.sgb.kjwl.di.self.DaggerSelfComponent;
import com.sgb.kjwl.di.self.SelfModule;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.kjwl.model.entity.user.AddCarEntity3;
import com.sgb.kjwl.model.entity.user.CommonPickerEntity3;
import com.sgb.kjwl.utils.EditInputFilter;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LeaseCarPublishEvent;
import com.sgb.kjwl.viewmodel.self.publish.CarPublishModel2;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.util.MToast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import javax.inject.Inject;

/**
 * 车辆发布步骤2
 */
public class CarPublishActivity2 extends AppActivity implements ItemInputTextView.OnWholeItemClickListener {
    private ActivityCarPublish2Binding binding;

    @Inject
    CarPublishModel2 viewModel;

    private int rentPosition;
    private List<CommonPickerEntity3> rentEntityList;
    private List<PickSelectEntity> invoiceDatas, invoiceGGDatas;
    private List<PickSelectEntity> tariffDatas = new ArrayList<>();

    public static void start(Context context) {
        start(context, null);
    }

    public static void start(Context context, Intent extras) {
        Intent intent = new Intent();
        intent.setClass(context, CarPublishActivity2.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        if (extras != null) {
            intent.putExtras(extras);
        }
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerSelfComponent.builder()
                .appComponent(appComponent)
                .selfModule(new SelfModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

        setTileImmerse(true);

        initInvoiceData();
        viewModel.getLeaseRate();
    }


    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(CarPublishActivity2.this, R.layout.activity_car_publish2);
        binding.setViewModel(viewModel);
        binding.topLayout.titleView.setText("车辆出租发布 2/3");
        binding.topLayout.ivBack.setOnClickListener(this);
        binding.preView.setOnClickListener(this);
        binding.nextView.setOnClickListener(this);
        binding.itemTvOut.setOnClickListener(this);
        binding.itemTvInvoice.setOnWholeItemClickListener(this);
        binding.itemTvInvoiceGg.setOnWholeItemClickListener(this);
        binding.itemTvSl.setOnWholeItemClickListener(this);
//        binding.itemTvSl.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
//        binding.itemTvSl.setCheck(2, 2);
        binding.itemTvMoney.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED);
        binding.itemTvMoney.setFilters(new EditInputFilter[]{new EditInputFilter(99999999.99, 2)});
        binding.itemTvPay.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED);
        binding.itemTvPay.setFilters(new EditInputFilter[]{new EditInputFilter(99999999.99, 2)});
        binding.itemTvWeek.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED);
        binding.itemTvWeek.setFilters(new EditInputFilter[]{new EditInputFilter(99999999.99, 2)});
        binding.itemTvMonth.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED);
        binding.itemTvMonth.setFilters(new EditInputFilter[]{new EditInputFilter(99999999.99, 2)});
        binding.itemTvYear.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED);
        binding.itemTvYear.setFilters(new EditInputFilter[]{new EditInputFilter(99999999.99, 2)});
        binding.itemTvOutContent.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED);
        binding.itemTvOutContent.setFilters(new EditInputFilter[]{new EditInputFilter(99999999.99, 2)});
    }

    /**
     *
     */
    //初始化发票选择数据
    private void initInvoiceData() {
        //是否选择发票（0:是;1:否）
        invoiceDatas = new ArrayList<>();
        invoiceDatas.add(new PickSelectEntity("1", "是"));
        invoiceDatas.add(new PickSelectEntity("0", "否"));
        //发票类型
        invoiceGGDatas = new ArrayList<>();
        invoiceGGDatas.add(new PickSelectEntity("0", "普通发票"));
        invoiceGGDatas.add(new PickSelectEntity("1", "专用发票"));

        //设置默认选择
        if (TextUtils.isEmpty(viewModel.addCarEntity.get().getNeedInvoice())) {//数据为空,代表新增
            binding.itemTvInvoice.setContent("是");
            binding.itemTvInvoiceGg.setContent("普通发票");
            Objects.requireNonNull(viewModel.addCarEntity.get()).setNeedInvoice("1");
            Objects.requireNonNull(viewModel.addCarEntity.get()).setInvoiceType("0");
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void OnWholeItemClick(View view) {
        switch (view.getId()) {
            case R.id.item_tv_invoice://是否提供发票
                if (null != invoiceDatas && invoiceDatas.size() > 0) {
                    OptionsPickerView businessOption = new OptionsPickerBuilder(CarPublishActivity2.this, (options1, options2, options3, v) -> {
                        String content = invoiceDatas.get(options1).getProjectscale();
                        binding.itemTvInvoice.setContent(content);
                        Objects.requireNonNull(viewModel.addCarEntity.get()).setNeedInvoice(invoiceDatas.get(options1).getNo());
                        if ("否".equals(content)) {
                            binding.itemTvInvoiceGg.setVisibility(View.GONE);
                            binding.itemTvSl.setVisibility(View.GONE);
                        } else {
                            binding.itemTvInvoiceGg.setVisibility(View.VISIBLE);
                            binding.itemTvSl.setVisibility(View.VISIBLE);
                        }
                    }).build();
                    businessOption.setPicker(invoiceDatas);
                    businessOption.setSelectOptions(0);
                    businessOption.show();
                }
                break;
            case R.id.item_tv_invoice_gg://发票类型
                if (null != invoiceGGDatas && invoiceGGDatas.size() > 0) {
                    OptionsPickerView businessOption = new OptionsPickerBuilder(CarPublishActivity2.this, (options1, options2, options3, v) -> {
                        String content = invoiceGGDatas.get(options1).getProjectscale();
                        binding.itemTvInvoiceGg.setContent(content);
                        Objects.requireNonNull(viewModel.addCarEntity.get()).setInvoiceType(invoiceGGDatas.get(options1).getNo());
                    }).build();
                    businessOption.setPicker(invoiceGGDatas);
                    businessOption.setSelectOptions(0);
                    businessOption.show();
                }
                break;
            case R.id.item_tv_sl://税率
                if (null != tariffDatas && tariffDatas.size() > 0) {
                    OptionsPickerView businessOption = new OptionsPickerBuilder(CarPublishActivity2.this, (options1, options2, options3, v) -> {
                        binding.itemTvSl.setContent(tariffDatas.get(options1).getProjectscale());
                        viewModel.addCarEntity.get().setTariff(tariffDatas.get(options1).getNo());
                    }).build();
                    businessOption.setPicker(tariffDatas);
                    businessOption.setSelectOptions(0);
                    businessOption.show();
                }
                break;
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.next_view:
                validity();
                break;
            case R.id.pre_view:
            case R.id.iv_back:
                saveAddCarEntity();
                EventBus.getDefault().post(LeaseCarPublishEvent.make().setMessageTag(EventConstant.EVENT_CAR_INFO_PUBLISH).setMessageData(viewModel.addCarEntity.get()));
                finish();
                break;
            case R.id.item_tv_out:
                if (rentEntityList != null) {
                    showRentPicker(rentEntityList);
                } else {
                    viewModel.getPickercarRent();
                }
                break;
        }
    }

    private void validity() {
        if (TextUtils.isEmpty(binding.itemTvMoney.getContent())) {
            MToast.showToast(CarPublishActivity2.this, "请输入车辆押金");
            return;
        }
        if (Double.parseDouble(binding.itemTvMoney.getContent()) <= 0) {
            MToast.showToast(CarPublishActivity2.this, "请输入大于0的车辆押金");
            return;
        }
        if (TextUtils.isEmpty(binding.itemTvPay.getContent())) {
            MToast.showToast(CarPublishActivity2.this, "请输入日租金");
            return;
        }
        if (Double.parseDouble(binding.itemTvPay.getContent()) <= 0) {
            MToast.showToast(CarPublishActivity2.this, "请输入大于0的日租金");
            return;
        }

        if (!TextUtils.isEmpty(binding.itemTvWeek.getContent()) && Double.parseDouble(binding.itemTvWeek.getContent()) <= 0) {
            MToast.showToast(CarPublishActivity2.this, "请输入大于0的周租金");
            return;
        }
        if (!TextUtils.isEmpty(binding.itemTvMonth.getContent()) && Double.parseDouble(binding.itemTvMonth.getContent()) <= 0) {
            MToast.showToast(CarPublishActivity2.this, "请输入大于0的月租金");
            return;
        }
        if (!TextUtils.isEmpty(binding.itemTvYear.getContent()) && Double.parseDouble(binding.itemTvYear.getContent()) <= 0) {
            MToast.showToast(CarPublishActivity2.this, "请输入大于0的年租金");
            return;
        }
        if (!TextUtils.isEmpty(binding.itemTvOutContent.getText()) && Double.parseDouble(binding.itemTvOutContent.getText().toString()) <= 0) {
            MToast.showToast(CarPublishActivity2.this, "请输入大于0的超时计费价格");
            return;
        }

        if (binding.itemTvInvoice.getContent().equals("是")) {
            if (TextUtils.isEmpty(binding.itemTvSl.getContent())) {
                MToast.showToast(CarPublishActivity2.this, "请填写税率");
                return;
            }
        }

        Objects.requireNonNull(viewModel.addCarEntity.get()).getAddCarLeaseEntity3().setLeaseDayMoney(binding.itemTvPay.getContent());
        Objects.requireNonNull(viewModel.addCarEntity.get()).getAddCarLeaseEntity3().setLeaseWeekMoney(binding.itemTvWeek.getContent());
        Objects.requireNonNull(viewModel.addCarEntity.get()).getAddCarLeaseEntity3().setLeaseMonthMoney(binding.itemTvMonth.getContent());
        Objects.requireNonNull(viewModel.addCarEntity.get()).getAddCarLeaseEntity3().setLeaseYearMoney(binding.itemTvYear.getContent());
        Objects.requireNonNull(viewModel.addCarEntity.get()).getAddCarLeaseEntity3().setLeaseCarMoney(binding.itemTvMoney.getContent());
        Objects.requireNonNull(viewModel.addCarEntity.get()).getAddCarLeaseEntity3().setLeaseOutMoney(binding.itemTvOutContent.getText().toString());
        Objects.requireNonNull(viewModel.addCarEntity.get()).getAddCarLeaseEntity3().setLeaseOtherNote(binding.cfkEditView.getEditContent());

        EventBus.getDefault().postSticky(LeaseCarPublishEvent.make().setMessageTag(EventConstant.EVENT_CAR_CONTACT_PUBLISH).setMessageData(viewModel.addCarEntity.get()));
        CarPublishActivity3.start(CarPublishActivity2.this);
    }

    public void showRentPicker(List<CommonPickerEntity3> rentEntityList) {
        this.rentEntityList = rentEntityList;
        OptionsPickerView businessOption = new OptionsPickerBuilder(CarPublishActivity2.this, (options1, options2, options3, v) -> {
            String content = rentEntityList.get(options1).getName();
            binding.itemTvOutRight.setText(content);
            rentPosition = options1;
            Objects.requireNonNull(viewModel.addCarEntity.get()).getAddCarLeaseEntity3().setUnit(rentEntityList.get(options1).getId());
            Objects.requireNonNull(viewModel.addCarEntity.get()).getAddCarLeaseEntity3().setUnitLabel(content);
        }).build();
        businessOption.setPicker(rentEntityList);
        businessOption.setSelectOptions(rentPosition);
        businessOption.show();
    }

    //税率
    public void showRate(List<PickSelectEntity> list) {
        tariffDatas = list;
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(LeaseCarPublishEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_CAR_LEAS_PUBLISH) {
            AddCarEntity3 addCarEntity3 = (AddCarEntity3) event.getMessageData();
            viewModel.addCarEntity.set(addCarEntity3);
            showEdit();
            EventBus.getDefault().removeStickyEvent(event);
        } else if (event.getMessageTag() == EventConstant.EVENT_CAR_PUBLISH_FINISH) {
            finish();
        }
    }

    private void showEdit() {
        if (viewModel.addCarEntity.get().getAddCarLeaseEntity3() != null) {
            if (!TextUtils.isEmpty(viewModel.addCarEntity.get().getAddCarLeaseEntity3().getUnitLabel())) {
                binding.itemTvOutRight.setText(viewModel.addCarEntity.get().getAddCarLeaseEntity3().getUnitLabel());
            }
        }

        if ("1".equals(viewModel.addCarEntity.get().getNeedInvoice())) {
            binding.itemTvInvoice.setContent("是");
            binding.itemTvSl.setVisibility(View.VISIBLE);
            binding.itemTvSl.setContent(viewModel.addCarEntity.get().getTariff() + "%");
            binding.itemTvInvoiceGg.setVisibility(View.VISIBLE);
            if ("0".equals(viewModel.addCarEntity.get().getInvoiceType())) {
                binding.itemTvInvoiceGg.setContent("普通发票");
            } else {
                binding.itemTvInvoiceGg.setContent("专用发票");
            }
        } else if ("0".equals(viewModel.addCarEntity.get().getNeedInvoice())) {
            binding.itemTvInvoice.setContent("否");
            binding.itemTvInvoiceGg.setVisibility(View.GONE);
            binding.itemTvSl.setVisibility(View.GONE);
        } else {//如果没有没有数据,代表是新发布,默认开具发票
            binding.itemTvInvoice.setContent("是");
            binding.itemTvInvoiceGg.setContent("普通发票");
            Objects.requireNonNull(viewModel.addCarEntity.get()).setNeedInvoice("1");
            Objects.requireNonNull(viewModel.addCarEntity.get()).setInvoiceType("0");
        }

        if (!TextUtils.isEmpty(viewModel.addCarEntity.get().getAddCarLeaseEntity3().getUnitLabel())) {
            binding.itemTvOutRight.setText(viewModel.addCarEntity.get().getAddCarLeaseEntity3().getUnitLabel());
        }


    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void saveAddCarEntity() {
        Objects.requireNonNull(viewModel.addCarEntity.get()).getAddCarLeaseEntity3().setLeaseDayMoney(binding.itemTvPay.getContent());
        Objects.requireNonNull(viewModel.addCarEntity.get()).getAddCarLeaseEntity3().setLeaseWeekMoney(binding.itemTvWeek.getContent());
        Objects.requireNonNull(viewModel.addCarEntity.get()).getAddCarLeaseEntity3().setLeaseMonthMoney(binding.itemTvMonth.getContent());
        Objects.requireNonNull(viewModel.addCarEntity.get()).getAddCarLeaseEntity3().setLeaseYearMoney(binding.itemTvYear.getContent());
        Objects.requireNonNull(viewModel.addCarEntity.get()).getAddCarLeaseEntity3().setLeaseCarMoney(binding.itemTvMoney.getContent());
        Objects.requireNonNull(viewModel.addCarEntity.get()).getAddCarLeaseEntity3().setLeaseOutMoney(binding.itemTvOutContent.getText().toString());
        Objects.requireNonNull(viewModel.addCarEntity.get()).getAddCarLeaseEntity3().setLeaseOtherNote(binding.cfkEditView.getEditContent());
    }
}

